
// 定点着色器
const vss_s = `
  attribute vec4 a_Position;
  // attribute vec4 a_Position;
  uniform float u_SinB, u_CosB;
  void main() {
    // gl_Position = a_Position;
    gl_Position.x = a_Position.x * u_CosB - a_Position.y * u_SinB;
    gl_Position.y = a_Position.x * u_SinB + a_Position.y * u_CosB;
    gl_Position.z = 0.0;
    gl_Position.w = 1.0;
  }
`;

// 片元着色器
const  fs_s = `
  void main() {
    gl_FragColor = vec4(1.0, 0, 0, 1);
  }
`;


const Angle = 90.0;

function main() {
  const canvas = document.getElementById('webgl');
  if (!canvas) {
    alert('Field to get element by id.');
    return false;
  }
  const gl = canvas.getContext('webgl');
  if (!gl) {
    alert('Field to get gl by canvas');
    return false;
  }
  if (!initShaders(gl, vss_s, fs_s)) {
    alert('Field to init shaders.');
    return false;
  }
  const pointCount = initVertexPoints(gl);
  if (pointCount < 0) {
    alert('Field to init vertex points.');
    return false;
  }

  const randomAngle = Math.PI * Angle / 180.0;
  const cosB = Math.cos(randomAngle);
  const sinB = Math.sign(randomAngle);
  const u_CosB = gl.getUniformLocation(gl.program, 'u_CosB');
  gl.uniform1f(u_CosB, cosB);
  const u_SinB = gl.getUniformLocation(gl.program, 'u_SinB');
  gl.uniform1f(u_SinB, sinB);

  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, pointCount);
}

function initVertexPoints(gl) {
  // 定义 定点坐标 数据
  const vertices = new Float32Array([
    0, 0.5,
    0.5, 0,
    0, -0.5,
  ]);

  // 创建 buffer
  const vertexBuffer = gl.createBuffer();
  if (!vertexBuffer) {
    alert('Field to create buffer');
    return -1;
  }
  // 绑定 buffer 到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 将 顶点坐标 数据 写入到 缓存区
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  // 获取 定点坐标变量
  const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if (a_Position < 0) {
    alert('Field to get position');
    return -1;
  }
  // 分配 缓存区数据 到 顶点坐标变量
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
  // 激活缓存区
  gl.enableVertexAttribArray(a_Position);
  return Math.ceil(vertices.length / 2);
}